<?php
class TempController extends NodeController
{
    /**
     * 模板编辑
     */
    public function tempList ()
    {
        /* 分页如何缓存 */
        if (isset($_GET['p'])) {
            $cache_id = $_GET['p'];
        }
        // 默认设置为15条
        if ($_GET['num'] > 0) {
            $num = trim($_GET['num']);
        } else {
            $newNum = require 'config/base.php';
            $num = $newNum['pagenum'];
        }
        $num = 500;
        // $num = 20;
        // $totalNum = 2000;
        $totalNum = 500;
        $page = $this->page($totalNum, $_GET['p'], $num);
        $this->view()->assign('num', $page);
        if ($_GET['type']) {
            $where = array('type' => $_GET['type']);
            $cache_id = $_GET['type'] . $cache_id;
        }
        $rs = NewsModel::instance()->getTemplateList($page['start'], 
        $page['num'], 'id,remark,name,action,type,modified', $where);
        $type = NewsModel::instance()->getTemplatesType();
        $temptype = array();
        foreach ($type as $k => $v) {
            $temptype[$v['id']] = $v['name'];
        }
        foreach ($rs as $k => $v) {
            $rs[$k]['type'] = $temptype[$v['type']];
        }
        // 并且显示历史版本
        $this->view()->assign('type', $type);
        $this->view()->assign('typeid', trim($_GET['type']));
        $this->view()->assign('totalnum', $totalNum);
        $this->view()->assign('templist', $rs);
        $this->view()->display('file:news/temp.list.tpl', $cache_id);
    }
    /**
     * 获取历史版本
     */
    public function history ()
    {
        if ($_GET['id'] > 0) {
            $id = $_GET['id'];
        }
        $rs = NewsModel::instance()->getTempHistory(array('temp_id' => $id), 
        'id,temp_id,date,remark,action');
        $this->view()->assign('templist', $rs);
        $this->view()->clearCache('file:news/temp.history.tpl');
        $this->view()->display('file:news/temp.history.tpl');
    }
    /**
     * 从历史模板中获取
     * Enter description here ...
     */
    private function getTempFromHistoryById ($id)
    {
        return NewsModel::instance()->getTempHistory(array('id' => $id), 
        'id,temp_id,date,remark,source,action');
    }
    /**
     * 从主模板中获取
     * Enter description here ...
     */
    private function getTempFromMainById ($id)
    {
        return NewsModel::instance()->getTemplateById($id);
    }
    private function getTempFromMainByName ($name)
    {
        return NewsModel::instance()->getTemplateByName($name);
    }
    /**
     * 
     * 处理单个模板信息
     * */
    private function parseTemp ($param, $type)
    {
        switch ($type) {
            case 1:
                $tempInfo = $this->getTempFromMainByName($param);
                break;
            case 2:
                $tempInfo = $this->getTempFromHistoryById($param);
                break;
            default:
                $tempInfo = $this->getTempFromMainById($param);
                break;
        }
        //获取最新的更新记录
        if ($type != 2) {
            $history = NewsModel::instance()->getTempHistory(
            array('temp_id' => $tempInfo['id']), 'id,temp_id,date,action', 1);
        }
        if (! empty($history)) {
            $tempInfo = array_merge($history[0], $tempInfo);
        }
        if ($type == 2) {
            $tempInfo = $tempInfo[0];
            $tempInfo['id'] = $tempInfo['temp_id'];
        }
        // 并且记录日志
        // 修正bug 对$tempInfo 进行匹配
        $tempInfo['source'] = preg_replace("#</textarea>#is", 
        "<\/textarea>", $tempInfo['source']);
        $tempInfo['size'] = $this->filesize(strlen($tempInfo['source']));
        return $tempInfo;
    }
    /**
     * 编辑模板 来源历史模板或者主模板
     */
    public function editTemp ()
    {
        // 从分类编辑进入
        if (isset($_GET['id'])) {
            $param = $_GET['id'];
        }
        if ($_GET['name']) {
            $type = 1;
            $param = $_GET['name'];
        }
        if ($_GET['type'] == 'history') {
            $type = 2;
        }
        //这部分代码不应该放在这里
        $tempInfo = $this->parseTemp($param, $type);
        $this->view()->assign('tempinfo', $tempInfo);
        $this->view()->display('file:news/edit_temp.tpl');
    }
    /**
     * 返回kb
     * @param unknown_type $size
     */
    private function filesize ($size)
    {
        switch ($size) {
            case $size < 1024:
                return $size . " Bytes";
                ;
                break;
            case $size >= 1024:
                return round($size / 1024, 2) . " Kb";
                break;
        }
    }
    /**
     * 保存分类
     */
    public function saveTemp ()
    {
        if ($_POST['id'] > 0) {
            $source = $_POST['source'];
            $id = $_POST['id'];
            $user = unserialize($_SESSION['uid']);
            // 保存历史记录
            $tempInfo = NewsModel::instance()->getTemplateById($id);
            $source = preg_replace("#<\/textarea>#is", "</textarea>", $source);
            $addTemp = NewsModel::instance()->addTempHistory(
            array('temp_id' => $id, 'source' => addslashes($tempInfo['source']), 
            'date' => time(), 'remark' => $_POST['remark'], 
            'action' => $user['username']));
            if (empty($addTemp)) {
                $this->sendNotice(FAILED);
            }
            // 如果没有开启转义
            if (! get_magic_quotes_gpc()) {
                $error = NewsModel::instance()->saveTempSource(
                addslashes($source), $id);
            } else {
                $error = NewsModel::instance()->saveTempSource($source, $id);
            }
            if (! empty($error[2])) {
                $this->sendNotice($error[2]);
            }
            //只保留最新10条记录
            $num = NewsModel::instance()->getTempHistory(
            array('temp_id' => $id), "id");
            if (count($num) >= 15) {
                asort($num);
                NewsModel::instance()->deleteTempHistory($id, $num[10][id]);
            }
            // 添加记录
            NewsModel::instance()->setTempldateStatus($id, 
            array('status' => 0));
            unset($_SESSION['isedit']);
            // echo '保存成功';
            $this->sendNotice(SUCCESS, NULL, true);
        }
    }
    /**
     * 添加模板
     */
    public function addTemp ()
    {
        // 引入分类
        // $this->view()->assign ( 'category', $this->getCategory () );
        // 检验模板名称是否已经存在
        if (isset($_POST) && ! empty($_POST['name'])) {
            $flag = NewsModel::instance()->getTemplateByName(
            trim($_POST['name']));
            if (! empty($flag)) {
                $this->sendNotice('temp name already exist', NULL, FALSE);
            }
            $result = NewsModel::instance()->addTemp(
            array('name' => trim($_POST['name']), 'remark' => $_POST['remark'], 
            'type' => $_POST['type']));
            $this->sendNotice(SUCCESS, NULL, TRUE);
        } else {
            $this->sendNotice('please set temp name', NULL, false);
            exit();
        }
        $this->view()->clearCache('file:news/addtemp.tpl');
        $this->view()->display('file:news/addtemp.tpl');
    }
}